/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
package com.wealth.commodity.web.controller;

import iaas.enums.StatusEnum;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.commodity.entity.Category;
import com.wealth.commodity.service.ICategoryService;
import com.wealth.merchant.entity.Market;
import com.wealth.merchant.service.IMarketService;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping(value = "/manage/commodity/category")
public class CategoryController extends BaseController {

	Logger logger = Logger.getLogger(CategoryController.class);

	@Autowired
	private ICategoryService categoryService;
	@Autowired
	private IMarketService marketService;

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		try {
			if (id != -1) {
				Category category = categoryService.get(id);
				model.addAttribute("category", category);
			}
		} catch (Exception e) {
			logger.error("初始化错误", e);
		}
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
		model.addAttribute("corpid", corpid);
		return "commodity/category/list";
	}

	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model, JqGridRequest request) {
		try {

			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();

			Page<Category> page = categoryService.get(corpid, request,
					Category.class);

			return JqGridUtil.getJqGrirdResponse(page);
		} catch (Exception e) {
			logger.error("列表错误！", e);
			return null;
		}
	}

	/**
	 * 详情
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String infoForm(Model model, @PathVariable("id") Long id) {
		try {
			Category category = categoryService.get(id);
			model.addAttribute("category", category);
			return "commodity/category/info";
		} catch (Exception e) {
			logger.error("详情页面错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 创建页面
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String createForm(Model model) {
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();

			// 查询市场
			List<Market> marketList = marketService.findByPropertyName(
					"status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("markets", marketList);

			return "commodity/category/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}

	/**
	 * 加载子节点
	 */
	@RequestMapping(value = "/ajaxChild", method = RequestMethod.POST)
	@ResponseBody
	public List<Category> ajaxChild(@RequestParam Long mid) {
		try {
			List<Category> categoryList = categoryService
					.getByMarketIdAndStatusAndPcategoryIsNull(mid,
							StatusEnum.NORMAL.getValue());
			return categoryList;
		} catch (Exception e) {
			logger.error("修改排序错误", e);
			return null;
		}
	}
	
	/**
	 * 分类名称是否唯一
	 * 2015-07-15 by chan
	 * ----------- 参数说明 ----------
	 * market 市场名称
	 * cname 父分类名
	 * name 子分类名
	 * 
	 * ----------- 返回说明 --------
	 * true 表示分类名称唯一
	 * false 表示存在相同的分类名称
	 */
	@RequestMapping(value="/unique/name",method = RequestMethod.POST)
	@ResponseBody
	public boolean unique(@RequestParam String name,@RequestParam Long pcategoryId,@RequestParam Long marketId){
		try{
			return categoryService.unique(name,StatusEnum.NORMAL.getValue(),pcategoryId,marketId);
		}catch(Exception e){
			logger.error("检查分类名称是否存在错误！！", e);
			return false;
		}
	}

	/**
	 * 创建
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(Model model, Category entity,
			RedirectAttributes redirectAttributes) {
		try {
			User user = ShiroUser.getInstance().getUser();
			if (entity.getPcategory().getId() == null) {
				entity.setPcategory(null);
			}
			entity.setCorp(user.getCorp());
			entity.setStatus(StatusEnum.NORMAL.getValue());
			entity.setCreator(user.getUsername());
			entity.setCreateTime(new Date());
			categoryService.save(entity);
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/commodity/category/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}

	/**
	 * 编辑页面
	 */
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String setUpdateForm(Model model, @PathVariable("id") Long id) {
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();

			Category category = categoryService.get(id);
			model.addAttribute("category", category);

			// 查询商品分类
			List<Category> categories = categoryService.findByStatusAndCorpIdAndMarketIdAndPcategoryIsNull(StatusEnum.NORMAL.getValue(), corpid,category.getMarket().getId());
			model.addAttribute("categories", categories);

			// 查询市场
			List<Market> marketList = marketService.findByPropertyName(
					"status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("markets", marketList);

			return "commodity/category/update";
		} catch (Exception e) {
			logger.error("编辑页面错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 修改信息
	 */
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,
			@ModelAttribute("category") Category entity,
			RedirectAttributes redirectAttributes) {
		try {
			if (entity.getPcategory().getId() == null) {
				entity.setPcategory(null);
			}
			categoryService.clear();
			categoryService.save(entity);
			redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipSuccess("编辑成功"));
			return "redirect:/manage/commodity/category/list";
		} catch (Exception e) {
			logger.error("编辑错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			categoryService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/commodity/category/list";
		} catch (Exception e) {
			logger.error("删除错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 停用
	 */
	@RequestMapping(value = "/disable/{id}", method = RequestMethod.GET)
	public String disable(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			categoryService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/commodity/category/list";
		} catch (Exception e) {
			logger.error("停用错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 启用
	 */
	@RequestMapping(value = "/enable/{id}", method = RequestMethod.GET)
	public String enable(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			categoryService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/commodity/category/list";
		} catch (Exception e) {
			logger.error("启用错误,id=" + id, e);
			return "system/500";
		}
	}
}